require('dotenv').config();
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;

// 存储订单信息的临时数据库（实际项目中应使用真正的数据库）
const orderDatabase = {
  123: {
    amount: 100,
    currency: 'cny',
    description: '测试支付',
    returnUrl: 'http://localhost:3000/payment-success',
    status: 'pending',
  },
};

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// 主页路由 - 检查是否有订单ID
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 接收订单支付请求的接口
app.get('/pay/:orderId', (req, res) => {
  const { orderId } = req.params;
  const { amount, currency = 'cny', description, returnUrl } = req.query;

  // 存储订单信息和回调地址
  orderDatabase[orderId] = {
    amount,
    currency,
    description: description || `订单 ${orderId}`,
    returnUrl,
    status: 'pending',
    createdAt: new Date(),
  };

  // 重定向到支付页面，并传递订单ID
  res.redirect(`/?orderId=${orderId}`);
});

// 创建支付意向API
app.post('/create-payment-intent', async (req, res) => {
  try {
    const { amount, currency = 'usd', description, orderId } = req.body;

    // 创建元数据对象
    const metadata = {};
    if (orderId) {
      metadata.orderId = orderId;
    }

    // 创建Stripe支付意向
    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount,
      currency: currency,
      description: description,
      metadata: metadata,
      automatic_payment_methods: {
        enabled: true,
      },
    });

    // 如果有订单ID，更新订单状态
    if (orderId && orderDatabase[orderId]) {
      orderDatabase[orderId].paymentIntentId = paymentIntent.id;
    }

    // 返回客户端密钥
    res.json({
      clientSecret: paymentIntent.client_secret,
      publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
    });
  } catch (error) {
    console.error('创建支付意向时出错:', error);
    res.status(500).json({ error: error.message });
  }
});

// 查询订单支付状态的API
app.get('/api/order/:orderId/status', (req, res) => {
  const { orderId } = req.params;

  if (!orderDatabase[orderId]) {
    return res.status(404).json({ error: '订单不存在' });
  }

  res.json({
    orderId,
    status: orderDatabase[orderId].status,
    paymentIntentId: orderDatabase[orderId].paymentIntentId || null,
  });
});

// 支付成功回调
app.post(
  '/webhook',
  bodyParser.raw({ type: 'application/json' }),
  async (req, res) => {
    const sig = req.headers['stripe-signature'];
    let event;

    try {
      // 使用Stripe验证webhook签名
      event = stripe.webhooks.constructEvent(
        req.body,
        sig,
        process.env.STRIPE_WEBHOOK_SECRET || 'your_webhook_secret'
      );
    } catch (err) {
      console.log(`Webhook错误: ${err.message}`);
      return res.status(400).send(`Webhook错误: ${err.message}`);
    }

    // 处理事件
    if (event.type === 'payment_intent.succeeded') {
      const paymentIntent = event.data.object;
      console.log(`PaymentIntent ID: ${paymentIntent.id} 支付成功`);

      // 获取订单ID并更新状态
      const orderId = paymentIntent.metadata.orderId;
      if (orderId && orderDatabase[orderId]) {
        orderDatabase[orderId].status = 'completed';
        console.log(`订单 ${orderId} 标记为已完成`);
      }
    } else if (event.type === 'payment_intent.payment_failed') {
      const paymentIntent = event.data.object;
      console.log(`PaymentIntent ID: ${paymentIntent.id} 支付失败`);

      // 获取订单ID并更新状态
      const orderId = paymentIntent.metadata.orderId;
      if (orderId && orderDatabase[orderId]) {
        orderDatabase[orderId].status = 'failed';
        console.log(`订单 ${orderId} 标记为失败`);
      }
    }

    res.json({ received: true });
  }
);

// 启动服务器
app.listen(port, () => {
  console.log(`服务器已启动: http://localhost:${port}`);
});
